/**
 * 负责用户注册，登陆，模块
 * Created by commy on 2015/4/29.
 */
var express = require('express'),
    bodyParser = require('body-parser'),
    app = module.exports = express(),
    redis = require('./redis'),
    qs = require('querystring'),
    connect = require('./mongodb'),
    merge = require('utils-merge'),
    eventProxy = require('eventproxy'),
    validator = require('validator'),
    models = require('./models'),
    Q = require('q');
// create application/json parser
var jsonParser = bodyParser.json()

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({extended: false})

app.post('/authcode/create', urlencodedParser, function (req, res, next) {

    models.User.find({phone: req.body.phone}).then(function (result) {
        if (result.length > 0) {
            res.status(503).json({state: 'error', error_msg: 'phoneNumber has been register'});
            return null;
        } else {
            return redis.multi()
                .set('authcode.' + req.body.phone, '123456')
                .expire('authcode.' + req.body.phone, 3600)
                .exec();
        }
    }).then(function(result){
        console.log(result);
        if(result)
        res.status(200).json({state: 'success'});

    }).then(null,function(err){
        console.log(err);
        res.status(503).json({state: 'error'});
    });

});

app.post('/create', urlencodedParser, function (req, res, next) {
    var ep = new eventProxy();
    ep.fail(next);
    var body = req.body;
    if (!body.authcode || !body.phone) {
        res.status(503).json({state: 'error'});
    } else {
        redis.get('authcode.' + body.phone).then(function (result) {
            if (body.authcode == result) {
                var user = new models.User({
                    phone: body.phone,
                    password: body.password,
                    date: new Date()
                });
                user.save(function(err,result){
                    console.log(result);
                    if(err){
                        return next(err);
                    }else{
                        var createCategory = ['上衣','裤子','鞋子','包包','配饰','收藏'];
                        var category = {
                            name:'',
                            optime:parseInt(Date.now()/1000),
                            count:0,
                            changeable:false,
                            user:result._id
                        };
                        Q.all(createCategory.map(function(item){
                            var deferred = Q.defer();
                            var categoryEntity = new models.Category(merge(category,{name:item}));
                            categoryEntity.save(function(err,result){
                                if(err){
                                    deferred.reject(new Error(err));
                                }else{
                                    console.log(arguments);
                                    deferred.resolve(result);
                                }
                            });
                            return deferred.promise;
                        })).then(function(){
                            return redis.del('authcode.' + body.phone);
                        }).then(function(){
                            res.status(200).json({state: 'success'});
                        },function(err){
                            console.log(err);
                            res.status(503).json({state: 'error'});
                        });
                    }
                });
            } else {
                return res.status(503).json({state: 'authcode error'});
            }
        });
    }

});

app.post('/login', urlencodedParser, function (req, res, next) {
    var ep = new eventProxy();
    var body = req.body;
    var sessionid = body.phone + Date.now();
    if (body.password && body.phone) {
        models.User.findOne({
            phone: body.phone,
            password: body.password
        }).then(function(result){
            console.log(result);
            if (result) {
                return redis.hset('sessionid', sessionid, result._id);
            } else {
                throw new Error('user is not register');
            }
        }).then(function(result){
            res.status(200).json({state: 'success', sessionid: sessionid})
        },function(err){
            console.log(err);
            res.status(503).json({state: 'error'});
        });
    } else {
        res.status(503).json({state: 'error'});
    }
});


app.get('/logout', function (req, res, next) {
    var sessionid = req.header('sessionid') || qs.parse(req.url.slice(req.url.indexOf('?') + 1)).sessionid;
    redis.hdel('sessionid', sessionid).then(function (result) {
        console.log(result);
        res.status(200).json({state: 'success'});
    });
});